/*
 *    Copyright 2009-2023 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.ryan.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * 分页多线程-本地线程变量
 */
public class PageHoder {
  private static String pageNo = "pageNo";
  private static String pageSize = "pageSize";
  private static String resultType = "resultType";
  private static String resultTypeList = "resultTypeList";
  private static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>(){
    protected Map<String, Object> initialValue() {
      return new HashMap<>();
    }
  };

  public static void put(String key, Object value) {
    (threadLocal.get()).put(key, value);
  }

  public static Object get(String key) {
    return (threadLocal.get()).get(key);
  }

  public static String getString(String key) {
    return (String) (threadLocal.get()).get(key);
  }

  private static Boolean getBool(String key) {
    Boolean value = (Boolean) ((threadLocal.get()).get(key));
    return value == null ? false : value;
  }

  public static Boolean isPage() {
    return getPageNo() != null;
  }

  public static Integer getPageNo() {
    Object o = get(pageNo);
    return (Integer) o;
  }

  public static void setPageNo(Integer pageNo) {
    put(PageHoder.pageNo, pageNo);
  }

  public static Integer getPageSize() {
    Object o = get(pageSize);
    return (Integer) o;
  }

  public static void setPageSize(Integer pageSize) {
    put(PageHoder.pageSize, pageSize);
  }

  public static void setResultType(Class<?> type) {
    put(resultType, type);
  }

  public static Class<?> getResultType() {
    return (Class<?>) (get(resultType));
  }

  public static void setResultTypeList(boolean isList) {
    put(resultTypeList, isList);
  }

  public static boolean isResultTypeList() {
    Object rs = get(resultTypeList);
    return rs == null ? false : (Boolean) rs;
  }

  public static void clear() {
    setPageSize(null);
    setPageNo(null);
    setResultTypeList(false);
    setResultType(null);
  }
}
